﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

/*
    Socket1项目，主要弄清楚socket的初始化及怎样发送消息、接受消息
    Socket2项目，将Socket1项目稍微修改，实现客户端和服务端对话
*/
namespace Sokect2.Server
{
    class Program
    {
        static void Main(string[] args)
        {
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            IPEndPoint ipe = new IPEndPoint(ip, 5001);
            //1.建立一个Socket对象
            Socket socketServer = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);
            //2.Socket关联到这个IP上面
            socketServer.Bind(ipe);
            socketServer.Listen(8);
            Console.WriteLine("正在监听...");
            //接收发送连接信息的客户端(一直等待客户端连接，不继续执行)
            Socket acceptSocket = socketServer.Accept();
            Console.WriteLine("连接成功！！");
            //接受输入信息
            string inputMsg = string.Empty;
            //保存接受到的信息
            string message = string.Empty;
            while (true)
            {
                byte[] receiveBytes = new byte[2048];
                //服务端会一直等待客户端发送消息过来，否则不继续执行
                int byteLen = acceptSocket.Receive(receiveBytes, receiveBytes.Length, 0);
                message = Encoding.UTF8.GetString(receiveBytes, 0, byteLen);
                Console.WriteLine("客户端说：" + message);

                Console.WriteLine("请您输入信息给客户端（输入exit退出对话）：");
                inputMsg = Console.ReadLine();
                if (inputMsg.ToLower() == "exit")//退出对话
                {
                    break;
                }
                byte[] sendBytes = Encoding.UTF8.GetBytes(inputMsg);
                acceptSocket.Send(sendBytes, sendBytes.Length, 0);
            }
            //释放Socket占用的资源
            acceptSocket.Dispose();
            socketServer.Dispose();

            Console.ReadKey();
        }
    }
}
